package a_doubleWrite;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * todo
 *
 * @author luolidong
 * @version 1.0
 * @create 2021-07-26 19:02
 */
public class Sqrt {
    public double sqrt(int v, double t) {
        if (v < 0) throw new RuntimeException("负数不能开方");
        //牛顿迭代法
        double x = v;
        double y = (x + v / x) / 2;
        while (Math.abs(y - x) > t) {
            x = y;
            y = (x + v / x) / 2;
        }
        return y;
    }

    public double sqrt1(int v, double t) {
        //二分法
        double l = 0;
        double r = v;
        double mid = (r - l) / 2 + l;

        while (Math.abs(mid * mid - v) > t) {
            if (mid * mid > v) {
                r = mid;
            } else {
                l = mid;
            }
            mid = (r - l) / 2 + l;
        }
        return mid;
    }

    public static void main(String[] args) {
        Sqrt sqrt = new Sqrt();
        double sqrt1 = sqrt.sqrt(3, 0.01);
        System.out.println(Math.sqrt(3));
        System.out.println(sqrt1);
        double sqrt2 = sqrt.sqrt1(3, 0.01);
        System.out.println(sqrt2);
    }
}
